const program = require('commander')
const download = require('download-git-repo')
// init交互命令
const inquirer = require('inquirer')
const handlebars = require('handlebars')
const ora = require('ora')
const fs = require('fs')
const chalk = require('chalk')
const symbols = require('log-symbols')



program.version('1.0.0', '-v, --version')
        .command('init <name>')
        .action( name => {
            console.log(name, fs.existsSync(name))
            if (!fs.existsSync(name)) {
                inquirer.prompt([
                    {name: 'description', message: '请输入项目描述'},
                    {name: 'author', message: '请输入作者名称'}
                ]).then(answers => {
                    console.log(name)
                    const spinner = ora('正在下载模板...')
                    spinner.start();
                    download('dorothyDing/test_cli', name, function (err) {
                        // console.log(err ? 'download Error': 'down Success')
                        if (err) {
                            spinner.fail()
                            console.log(symbols.err, chalk.red(err))
                        } else {
                            spinner.succeed()
    
                            const fileName = `${name}/package.json}`
    
                            const meta = {
                                name,
                                description: answers.description,
                                author: answers.author
                            }
                            if (fs.existsSync(fileName)) {
                                const content = fs.readFileSync(fileName).toString()
                                const result = handlebars.compile(content)(meta)
                                fs.writeFileSync(fileName, result)
                            }
                            
                            console.log(symbols.success, chalk.green('项目初始化成功'))
                        }
                        
                    })
                })
            } else {
                console.log(symbols.err, chalk.red('项目已存在'))
            }
        })

program.parse(process.argv)
